//
//  ZSHUDManager.m
//  ZSHUDManager
//
//  Created by 字节科技 on 2018/12/20.
//  Copyright © 2018 Byte. All rights reserved.
//

#import "ZSHUDManager.h"
#define  LAYERWIDTH 40




@interface HUDView : UIButton
-(instancetype)initWithFrame:(CGRect)frame type:(HUDViewState)state text:(NSString *)text;
@property(nonatomic,strong)UILabel *titleL;
@property(nonatomic,strong)UIButton *closeBT;
@property(nonatomic,strong)UITextView *infoTV;
@end

@implementation HUDView{
    UIView * _logoView;
}
- (instancetype)initWithFrame:(CGRect)frame type:(HUDViewState)state text:(NSString *)text
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.masksToBounds = YES;
        
        [self cornerRadiusWithValue:4 radiusType:UIRectCornerAllCorners];
        switch (state) {
                
            case HUDViewStateSuccess:
                self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.9];
                [self drawSuccessLineWithText:text];
                break;
            case HUDViewStateFail:
                self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.9];
                [self drawFailLineWithText:text];
                break;
                
            default:
                break;
        }
        
    }
    return self;
}
-(void)drawSuccessLineWithText:(NSString *)text{
    [_logoView removeFromSuperview];
    CGFloat logoW =  MIN(self.width*0.35, KiosScaleW(35));
    _logoView=[[UIView alloc]initWithFrame:CGRectMake((self.width - logoW)*0.5, KiosScaleH(10),logoW, logoW)];
    [self addSubview:_logoView];
    //曲线建立开始点和结束点
    //1. 曲线的中心
    //2. 曲线半径
    //3. 开始角度
    //4. 结束角度
    //5. 顺/逆时针方向
    UIBezierPath * path=[UIBezierPath bezierPathWithArcCenter:CGPointMake(logoW*0.5, logoW*0.5) radius:logoW*0.5 startAngle:-M_PI endAngle:M_PI clockwise:YES];
    //对拐角和中心处理
    path.lineCapStyle=kCGLineCapRound;
    path.lineJoinStyle=kCGLineCapRound;
    
    
    //对号第一部分的起始
    
    [path moveToPoint:CGPointMake(logoW/5, logoW/2)];
    CGPoint pl =CGPointMake(logoW/5*2, logoW/4*3);
    [path addLineToPoint:pl];
    
    //对号第二部分起始
    CGPoint p2 = CGPointMake(logoW/8.0*6.5, logoW/4.f+2);
    [path addLineToPoint:p2];
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    //内部填充颜色
    layer.fillColor = [UIColor clearColor].CGColor;
    //线条颜色
    layer.strokeColor = [UIColor whiteColor].CGColor;
    //线条宽度
    layer.lineWidth = 3;
    layer.path = path.CGPath;
    //动画设置
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:NSStringFromSelector(@selector(strokeEnd))];
    animation.fromValue = @0;
    animation.toValue = @1;
    animation.duration = 0.5;
    [layer addAnimation:animation forKey:NSStringFromSelector(@selector(strokeEnd))];
    [_logoView.layer addSublayer:layer];
    
    self.titleL.text = text;
    self.titleL.textColor = [UIColor whiteColor];
    self.titleL.textAlignment = NSTextAlignmentCenter;
    self.titleL.numberOfLines = 4;
//    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.equalTo(self.mas_width).offset(-KiosScaleW(20));
//        make.centerX.equalTo(self);
//        make.top.equalTo(self->_logoView.mas_bottom).offset(KiosScaleH(10));
//    }];
    CGFloat titleY = KiosScaleH(20)+logoW;
    self.titleL.frame = CGRectMake(KiosScaleW(5),titleY , self.width-KiosScaleW(10), self.height - titleY);

    __weak typeof(*&self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf removeFromSuperview];
    });
    
    
}
-(void)drawFailLineWithText:(NSString *)text{
    [_logoView removeFromSuperview];
    CGFloat logoW =  MIN(self.width*0.35, KiosScaleW(35));
    _logoView=[[UIView alloc]initWithFrame:CGRectMake((self.width - logoW)*0.5, KiosScaleH(10),logoW, logoW)];
    [self addSubview:_logoView];
    
    UIBezierPath * path=[UIBezierPath bezierPathWithArcCenter:CGPointMake(logoW*0.5, logoW*0.5) radius:logoW*0.5 startAngle:-M_PI endAngle:M_PI clockwise:YES];
    //对拐角和中心处理
    path.lineCapStyle=kCGLineCapRound;
    path.lineJoinStyle=kCGLineCapRound;
    
    //错号第一部分的起始
    [path moveToPoint:CGPointMake(logoW/4, logoW/4)];
    CGPoint pl =CGPointMake(logoW/4*3, logoW/4*3);
    [path addLineToPoint:pl];
    //错号第二部分起始
    [path moveToPoint:CGPointMake(logoW/4*3, logoW/4)];
    
    CGPoint p2 = CGPointMake(logoW/4.0, logoW/4*3);
    [path addLineToPoint:p2];
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    //内部填充颜色
    layer.fillColor = [UIColor clearColor].CGColor;
    //线条颜色
    layer.strokeColor = [UIColor whiteColor].CGColor;
    //线条宽度
    layer.lineWidth = 3;
    layer.path = path.CGPath;
    //动画设置
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:NSStringFromSelector(@selector(strokeEnd))];
    animation.fromValue = @0;
    animation.toValue = @1;
    animation.duration = 0.5;
    [layer addAnimation:animation forKey:NSStringFromSelector(@selector(strokeEnd))];
    
    [_logoView.layer addSublayer:layer];
    [self addSubview:_logoView];
    
    self.titleL.text = text;
    self.titleL.textColor = [UIColor whiteColor];
    self.titleL.textAlignment = NSTextAlignmentCenter;
    self.titleL.numberOfLines = 4;
//    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.equalTo(self.mas_width).offset(-KiosScaleW(20));
//        make.centerX.equalTo(self);
//        make.top.equalTo(self->_logoView.mas_bottom).offset(KiosScaleH(17));
//    }];
    CGFloat titleY = KiosScaleH(20)+logoW;
    self.titleL.frame = CGRectMake(KiosScaleW(5),titleY , self.width-KiosScaleW(10), self.height - titleY);
    __weak typeof(*&self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf removeFromSuperview];
    });
}
-(UILabel *)titleL{
    if (!_titleL) {
        _titleL = [[UILabel alloc]init];
        _titleL.font = KboldFont(15);
        _titleL.text = @"标题";
        [self addSubview:_titleL];
    }
    return _titleL;
}
@end


@interface ZSLoadingView : UIView
@property(nonatomic,strong)UILabel *titleL;
@end

@implementation ZSLoadingView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       
        [self creatCyclePath];
        CGFloat titleY = LAYERWIDTH+10;
        self.titleL.frame = CGRectMake(0, titleY, self.width, self.height - titleY);
        [self cornerRadiusWithValue:5 radiusType:UIRectCornerAllCorners];

    }
    return self;
}
-(void)creatCyclePath{
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake((self.width-LAYERWIDTH)/2, 15, LAYERWIDTH, LAYERWIDTH) cornerRadius:LAYERWIDTH/2.f];
    /// 底部的灰色layer
    CAShapeLayer *bottomShapeLayer = [CAShapeLayer layer];
    bottomShapeLayer.strokeColor = [UIColor colorWithRed:150/255.0 green:150/255.0 blue:150/255.0 alpha:1].CGColor;
    bottomShapeLayer.fillColor = [UIColor clearColor].CGColor;
    bottomShapeLayer.lineWidth = 3;
    bottomShapeLayer.path = bezierPath.CGPath;
    [self.layer addSublayer:bottomShapeLayer];
    /// 白色layer
    CAShapeLayer *ovalShapeLayer = [CAShapeLayer layer];
    ovalShapeLayer.strokeColor = [UIColor whiteColor].CGColor;
    ovalShapeLayer.fillColor = [UIColor clearColor].CGColor;
    ovalShapeLayer.lineWidth = 3;
    ovalShapeLayer.path = bezierPath.CGPath;
    //        ovalShapeLayer.lineDashPattern = @[@6,@2];
    [self.layer addSublayer:ovalShapeLayer];
    
    /// 起点动画
    CABasicAnimation * strokeStartAnimation = [CABasicAnimation animationWithKeyPath:@"strokeStart"];
    strokeStartAnimation.fromValue = @(-1);
    strokeStartAnimation.toValue = @(1.0);
    
    /// 终点动画
    CABasicAnimation * strokeEndAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    strokeEndAnimation.fromValue = @(0.0);
    strokeEndAnimation.toValue = @(1.0);
  
    /// 组合动画
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = @[strokeStartAnimation, strokeEndAnimation];
    animationGroup.duration = 1.5;
    animationGroup.repeatCount = CGFLOAT_MAX;
    animationGroup.fillMode = kCAFillModeForwards;
    animationGroup.removedOnCompletion = NO;
    [ovalShapeLayer addAnimation:animationGroup forKey:nil];
    self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.8];
    
}
- (UILabel *)titleL{
    if (!_titleL) {
        _titleL = [[UILabel alloc]init];
        _titleL.textAlignment = NSTextAlignmentCenter;
        _titleL.font = [UIFont boldSystemFontOfSize:14];
        _titleL.textColor = UIColor.whiteColor;
        [self addSubview:_titleL];
    }
    return _titleL;
}
@end




@implementation ZSHUDManager

+(void)showLoading:(NSString *)message{
    if (![NSThread isMainThread]) {
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
            ZSLoadingView*loadV = [[ZSLoadingView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
            loadV.titleL.text = message;
            loadV.center = keyWindow.center;
            [keyWindow addSubview:loadV];
        }];
        
    }else{
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        ZSLoadingView*loadV = [[ZSLoadingView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        loadV.titleL.text = message;
        loadV.center = keyWindow.center;
        [keyWindow addSubview:loadV];
    }
}
+(void)hideLoading{
    if ([NSThread isMainThread]) {
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        for (UIView *subV in keyWindow.subviews) {
            if ([subV isKindOfClass:[ZSLoadingView class]]) {
                [subV removeFromSuperview];
            }
        }
    }else{
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        for (UIView *subV in keyWindow.subviews) {
            if ([subV isKindOfClass:[ZSLoadingView class]]) {
                [subV removeFromSuperview];
            }
        }
    }
    
}
+(CGRect)rectWithString:(NSString *)str font:(UIFont *)font width:(CGFloat)width{
    
    return  [str boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil];
}
+(void)showAutoHiddenToastWithMessage:(NSString *)message{
    [self showToastWithMessage:message delay:1.5];
}

+(void)showToastWithMessage:(NSString *)message delay:(NSTimeInterval)delay{
    
  
    UIView *hudV = [self showToastWithMessage:message];
    __weak typeof(self) weakSelf = self;
    [self startShowWithView:hudV complete:^(BOOL isFinished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf hideHUdWithView:hudV];
        });
    }];

    
    
}

+(UIView *)showToastWithMessage:(NSString *)message{
   
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    CGRect messageRect = [self rectWithString:message font:KboldFont(18) width:kScreen_Width*0.7];
    UIButton *hudButton = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat buttonH = 0;
    if (IS_IPHONE) {
        NSLog(@"手机");
       buttonH = messageRect.size.height+10;
    }else{
        NSLog(@"平板");
       buttonH = messageRect.size.height+KiosScaleH(30);
    }
    hudButton.frame = CGRectMake(0, -buttonH, messageRect.size.width+KiosScaleW(30), buttonH);
    hudButton.centerX = keyWindow.centerX;
    [hudButton setTitle:message forState:UIControlStateNormal];
    hudButton.backgroundColor = RGBColor(0, 0, 0, 0.8);
    hudButton.titleLabel.font = KboldFont(18);
    [hudButton cornerRadiusWithValue:4 radiusType:UIRectCornerAllCorners];
    hudButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [hudButton setTitleEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [keyWindow addSubview:hudButton];
   
    return hudButton;
    
}
+(void)startShowWithView:(UIView *)subView complete:(void(^)(BOOL isFinished))isComplete{
   
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.35 initialSpringVelocity:0.6 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        subView.y = KiosScaleH(150);
    } completion:^(BOOL finished) {
        isComplete(finished);
    }];

}

+(void)hideHUdWithView:(UIView *)subV{
    
    if (subV&&[subV isKindOfClass:[UIButton class]]) {
        [UIView animateWithDuration:0.3 animations:^{
            subV.y = -subV.height;
        } completion:^(BOOL finished) {
            if (finished) {
                [subV removeFromSuperview];
            }
        }];
    }
    
}
+(void)showSuccess:(NSString *)message{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        
        CGRect messageRect = [self rectWithString:message font:KboldFont(15) width:kScreen_Width*0.45];

        CGFloat hudW = (messageRect.size.width +KiosScaleW(10))<KiosScaleW(100)?KiosScaleW(100):(messageRect.size.width +KiosScaleW(10));
        CGFloat hudH = (messageRect.size.height+KiosScaleH(55))<KiosScaleW(100)?KiosScaleW(100):(messageRect.size.height+KiosScaleH(55));
        HUDView *view = [[HUDView alloc]initWithFrame:CGRectMake(0, 0, hudW, hudH) type:HUDViewStateSuccess text:message];
        view.center = keyWindow.center;
        [keyWindow addSubview:view];
    });
    
}
+(void)showError:(NSString *)message{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        CGRect messageRect = [self rectWithString:message font:KboldFont(15) width:kScreen_Width*0.45];
        CGFloat hudW = (messageRect.size.width +KiosScaleW(10))<KiosScaleW(100)?KiosScaleW(100):(messageRect.size.width +KiosScaleW(10));
        CGFloat hudH = (messageRect.size.height+KiosScaleH(55))<KiosScaleW(100)?KiosScaleW(100):(messageRect.size.height+KiosScaleH(55));
        HUDView *view = [[HUDView alloc]initWithFrame:CGRectMake(0, 0, hudW, hudH) type:HUDViewStateFail text:message];
        view.center = keyWindow.center;
        [keyWindow addSubview:view];
    });
}
@end



@interface ZSUploadingView()
@property(nonatomic,strong)UILabel *progressL;

@end

@implementation ZSUploadingView
+(ZSUploadingView *)showUploading:(NSString *)message{
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    ZSUploadingView *uploadV = [[ZSUploadingView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    uploadV.center = keyWindow.center;
    uploadV.titleL.text = message;
    [keyWindow addSubview:uploadV];
    return uploadV;
}
-(void)hideUploading{
    [self removeFromSuperview];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self cornerRadiusWithValue:7 radiusType:UIRectCornerAllCorners];
        self.titleL.frame = CGRectMake(0, self.height -25, self.width, 20);
    }
    return self;
}
-(void)setProgress:(NSProgress *)progress{
    _progress = progress;
    self.floatProgress = (float)progress.completedUnitCount/(float)progress.totalUnitCount;
    self.progressL.text = [NSString stringWithFormat:@"%.0f%%",self.floatProgress*100];
}
-(void)setFloatProgress:(CGFloat)floatProgress{
    _floatProgress = floatProgress;
    self.progressL.text = [NSString stringWithFormat:@"%.0f%%",self.floatProgress*100];
    [self setNeedsDisplay];
}
-(void)drawRect:(CGRect)rect{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGFloat xCenter = rect.size.width*0.5;
    CGFloat yCenter = rect.size.height*0.5 - 10;
    [[UIColor whiteColor]set];
    CGContextSetLineWidth(ctx, 3);
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGFloat to = - M_PI * 0.5 + self.floatProgress * M_PI * 2 + 0.05; // 初始值0.05
    //半径
    CGFloat radius = MIN(rect.size.width, rect.size.height) * 0.25;
    CGContextAddArc(ctx, xCenter, yCenter, radius, - M_PI * 0.5, to, 0);
    CGContextStrokePath(ctx);
    self.progressL.centerX = xCenter;
    self.progressL.centerY = yCenter;
    
}
- (UILabel *)titleL{
    if (!_titleL) {
        _titleL = [[UILabel alloc]init];
        _titleL.textAlignment = NSTextAlignmentCenter;
        _titleL.font = [UIFont boldSystemFontOfSize:14];
        _titleL.textColor = UIColor.whiteColor;
        [self addSubview:_titleL];
    }
    return _titleL;
}
-(UILabel *)progressL{
    if (!_progressL) {
        _progressL = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
        _progressL.text = @"0%";
        _progressL.textColor = UIColor.whiteColor;
        _progressL.font = [UIFont boldSystemFontOfSize:13];
        _progressL.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_progressL];
    }
    return _progressL;
}
@end
